#include "widget_patient.h"
#include "ui_widget_patient.h"

Widget_patient::Widget_patient(QWidget *parent, QString userId, DoctorManagement *dm, PatientManagement *pm,
                               AppointmentManagement* am, AdviceManagement *adm, PrescriptionManagement *pscm,
                               MedicalRecordManagement *mrm)
    : QWidget(parent), ui(new Ui::Widget_patient), // 修改这里
      user_id(userId), d_m(dm), p_m(pm), a_m(am),
      ad_m(adm), psc_m(pscm), mr_m(mrm)
{
    ui->setupUi(this);
    initUserInfo();

    connect(this, &Widget_patient::requestShowHealthAssessmentClient,
               this, &Widget_patient::showHealthAssessmentClient);

    MainWidget* mainWidget = qobject_cast<MainWidget*>(parent);
    if (mainWidget) {
        // 连接信号和槽
        connect(this, &Widget_patient::requestChatClient, mainWidget, &MainWidget::handlePatientChatRequest);
    }
}

void Widget_patient::initUserInfo()
{
    QVariantMap userInfo = p_m->GetInfo(user_id); // 调用 GetInfo

    if (!userInfo.isEmpty()) {
        // 提取信息
        QString username = userInfo.value("username").toString();
        int age = userInfo.value("age").toInt();
        QString gender = userInfo.value("gender").toString();
        QString phone = userInfo.value("phone").toString();
        QString address = userInfo.value("address").toString();


        // 设置到界面组件

        ui->name_ld->setText(username);
        ui->age_ld->setText(QString::number(age));
        ui->gender_ld->setText(gender);
        ui->phone_ld->setText(phone);
        ui->address_ld->setText(address);
    } else {
        // 处理没有用户信息的情况
        ui->name_ld->setText("未找到用户信息");
        ui->age_ld->clear();
        ui->gender_ld->clear();
        ui->phone_ld->clear();
        ui->address_ld->clear();
    }
}

void Widget_patient::on_getPatientInfo_btn_clicked()
{
    ui->show->setCurrentIndex(0);
}

void Widget_patient::on_appointment_btn_clicked()
{
    ui->show->setCurrentIndex(1);
}

void Widget_patient::on_update_btn_clicked()
{
    QString name = ui->name_ld->text();
    int age = ui->age_ld->text().toInt();
    QString gender = ui->gender_ld->text();
    QString phone = ui->phone_ld->text();
    QString address = ui->address_ld->text();

    // 创建 JSON 对象并填充用户信息
    QJsonObject json_object;
    json_object["id"] = user_id;
    json_object["username"] = name;
    json_object["age"] = age;
    json_object["gender"] = gender;
    json_object["phone"] = phone;
    json_object["address"] = address;

    // 调用更新方法
    bool ret = p_m->Update(json_object);
    if(!ret) {
        LOG_ERROR() << "update patient information failed";
        Config::popMessageBox("OK", "修改信息成功", "error");
    } else {
        LOG_INFO() << "patient information updated successfully";
        Config::popMessageBox("OK", "修改信息成功", "ok");
    }
}

Widget_patient::~Widget_patient()
{
    delete ui;
}

void Widget_patient::on_pushButton_exit_clicked()
{
    this->close();
}

void Widget_patient::paintEvent(QPaintEvent *event)
{
    //    QPainter painter(this);
    //    QPixmap pixmap=QPixmap(":/bakground/image/patient_background.png");
    //    pixmap = pixmap.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    //    painter.drawPixmap(0,0,pixmap);
}

void Widget_patient::resizeEvent(QResizeEvent *event)
{
    update();
    QWidget::resizeEvent(event);
}

//void Widget_patient::connectToPatient() {
//    socket->connectToHost("127.0.0.1", 12345); // 连接到病人端的服务器
//    if (socket->waitForConnected()) {
//        qDebug() << "Connected to patient!";
//        socket->write("Hello, patient!");  // 发送消息
//    }
//}

void Widget_patient::on_profes_cbox_currentIndexChanged(const QString &arg1)
{
    updateDoctors(arg1);
}

// 更新医生下拉框
void Widget_patient::updateDoctors(const QString &profession)
{
    ui->doctor_cbox->clear();

    // 获取对应科室的医生列表
    QVariantList doctors = d_m->GetDoctorsByProfession(profession);

    // 检查获取的医生列表是否不为空
    if (!doctors.isEmpty()) {
        QStringList doctorNames;

        // 将 QVariantList 转换为 QStringList
        for (const QVariant &doctor : doctors) {
            doctorNames << doctor.toString();
        }

        // 添加医生到下拉框
        ui->doctor_cbox->addItems(doctorNames);
    }
}

void Widget_patient::on_submit_appoint_btn_clicked()
{
    QString selectedDoctor = ui->doctor_cbox->currentText();

    QString doctorId = d_m->GetIdByName(selectedDoctor);
    QString patientId = user_id;

    // 调用插入方法
    bool ret = a_m->Insert(doctorId, patientId);

    if (ret) {
        // 插入成功的处理
        QMessageBox::information(this, "成功", "预约成功！");
    } else {
        // 插入失败的处理
        QMessageBox::warning(this, "失败", "预约失败，请重试。");
    }
}

void Widget_patient::on_getDocInfo_btn_clicked() {
    ui->show->setCurrentIndex(2); // 切换到显示医生信息的页面

    QVariantMap doctorInfos = d_m->GetAllInfos();

    // 清空现有数据并重置行数
    ui->doctor_tab_widget->setRowCount(0); // 只重置行数

    // 设置表头（如果还未设置）
    if (ui->doctor_tab_widget->horizontalHeader()->count() == 0) {
        ui->doctor_tab_widget->setColumnCount(6); // 设置列数
        QStringList headers = { "用户名", "职业", "年龄", "性别", "电话", "地址" };
        ui->doctor_tab_widget->setHorizontalHeaderLabels(headers);
    }

    // 遍历 doctorInfos 并添加到 doctor_tab_widget
    for (const auto &key : doctorInfos.keys()) {
        const QVariantMap &info = doctorInfos.value(key).toMap(); // 获取每个医生的信息

        int row = ui->doctor_tab_widget->rowCount();
        ui->doctor_tab_widget->insertRow(row); // 插入新行

        // LOG_DEBUG() << "username: " << info.value("username").toString();

        // 将医生信息填充到对应的单元格中
        ui->doctor_tab_widget->setItem(row, 0, new QTableWidgetItem(info.value("username").toString()));
        ui->doctor_tab_widget->setItem(row, 1, new QTableWidgetItem(info.value("profession").toString()));
        ui->doctor_tab_widget->setItem(row, 2, new QTableWidgetItem(info.value("age").toString()));
        ui->doctor_tab_widget->setItem(row, 3, new QTableWidgetItem(info.value("gender").toString()));
        ui->doctor_tab_widget->setItem(row, 4, new QTableWidgetItem(info.value("phone").toString()));
        ui->doctor_tab_widget->setItem(row, 5, new QTableWidgetItem(info.value("address").toString()));
    }
}

void Widget_patient::on_getMedicalRecord_btn_clicked()
{
    ui->show->setCurrentIndex(3);

    // 获取病历信息
    // result:  QMap((details, QVariant(QString, 经常性的犯病，时而感到犯2b))(disease_name, QVariant(Invalid))(doctor_id, QVariant(int, 2))(record_date, QVariant(QString, 2024-11-02 11:24:59)))
    QVariantMap medical_records_info = mr_m->GetMedicalRecordByPID(user_id);

    // 清空现有数据并重置行数
    ui->medicalRecord_tab_widget->setRowCount(0); // 只重置行数

    // 设置表头（如果还未设置）
    if (ui->medicalRecord_tab_widget->horizontalHeader()->count() == 0) {
        ui->medicalRecord_tab_widget->setColumnCount(4); // 设置列数为4
        QStringList headers = { "医生姓名", "日期", "病名", "病历详情" };
        ui->medicalRecord_tab_widget->setHorizontalHeaderLabels(headers);
        // 设置列宽
        ui->medicalRecord_tab_widget->setColumnWidth(0, 150); // 医生姓名列宽
        ui->medicalRecord_tab_widget->setColumnWidth(1, 100); // 日期列宽
        ui->medicalRecord_tab_widget->setColumnWidth(2, 100); // 病名列宽
        ui->medicalRecord_tab_widget->setColumnWidth(3, 300); // 病历详情列宽
    }

    // 检查是否获取到病历信息
    if (!medical_records_info.isEmpty()) {
        // 获取医生 ID
        QString doctorId = medical_records_info["doctor_id"].toString();

        // 根据医生 ID 获取医生信息
        QVariantMap doctorInfo = d_m->GetInfo(doctorId);

        // 插入新行
        int row = ui->medicalRecord_tab_widget->rowCount();
        ui->medicalRecord_tab_widget->insertRow(row);

        // 填充医生姓名
        ui->medicalRecord_tab_widget->setItem(row, 0, new QTableWidgetItem(doctorInfo["username"].toString()));
        // 填充日期
        ui->medicalRecord_tab_widget->setItem(row, 1, new QTableWidgetItem(medical_records_info["record_date"].toString()));
        // 填充病名
        ui->medicalRecord_tab_widget->setItem(row, 2, new QTableWidgetItem(medical_records_info["disease_name"].toString()));
        // 填充病历详情
        ui->medicalRecord_tab_widget->setItem(row, 3, new QTableWidgetItem(medical_records_info["details"].toString()));
    } else {
        LOG_ERROR() << "No medical record found for user_id: " << user_id;
    }
}

void Widget_patient::on_getInstruction_btn_clicked()
{
    ui->show->setCurrentIndex(4);

    QVariantMap ins_docId_info = ad_m->GetInstructionByPID(user_id);

    // 清空现有数据并重置行数
    ui->instruction_tab_widget->setRowCount(0); // 只重置行数

    // 设置表头（如果还未设置）
    if (ui->instruction_tab_widget->horizontalHeader()->count() == 0) {
        ui->instruction_tab_widget->setColumnCount(4); // 设置列数为4
        QStringList headers = { "医嘱ID", "医生姓名", "医嘱", "日期" };
        ui->instruction_tab_widget->setHorizontalHeaderLabels(headers);
        // 设置列宽
        ui->instruction_tab_widget->setColumnWidth(0, 100); // 医嘱ID
        ui->instruction_tab_widget->setColumnWidth(1, 150); // 医生姓名列宽
        ui->instruction_tab_widget->setColumnWidth(2, 300); // 医嘱列宽
        ui->instruction_tab_widget->setColumnWidth(3, 100); // 日期列宽
    }

    // 检查是否获取到医嘱信息
    if (!ins_docId_info.isEmpty()) {
        int row = ui->instruction_tab_widget->rowCount();
        ui->instruction_tab_widget->insertRow(row); // 插入新行

        // 获取医生 ID
        QString doctorId = ins_docId_info["doctor_id"].toString();

        // 根据医生 ID 获取医生信息
        QVariantMap doctorInfo = d_m->GetInfo(doctorId);

        // 将数据填充到对应的单元格中
        ui->instruction_tab_widget->setItem(row, 0, new QTableWidgetItem(ins_docId_info["id"].toString())); // 医嘱ID
        ui->instruction_tab_widget->setItem(row, 1, new QTableWidgetItem(doctorInfo["username"].toString())); // 医生姓名
        ui->instruction_tab_widget->setItem(row, 2, new QTableWidgetItem(ins_docId_info["instruction"].toString())); // 医嘱

        // 设置当前日期
        QString currentDate = Config::getCurrentTime();
        ui->instruction_tab_widget->setItem(row, 3, new QTableWidgetItem(currentDate)); // 日期
    } else {
        LOG_ERROR() << "No instruction found for user_id: " << user_id;
    }
}



void Widget_patient::on_getPrescription_btn_clicked()
{
    ui->show->setCurrentIndex(5);

    // 获取处方信息
    QVariantMap prescription = psc_m->GetPrescriptionByPID(user_id);

    // 清空现有数据并重置行数
    ui->prescription_tab_widget->setRowCount(0);

    // 设置表头（如果还未设置）
    if (ui->prescription_tab_widget->horizontalHeader()->count() == 0) {
        ui->prescription_tab_widget->setColumnCount(6); // 设置列数为6
        QStringList headers = { "日期", "药品名", "使用频次", "剂量", "开销", "对应的医嘱ID" };
        ui->prescription_tab_widget->setHorizontalHeaderLabels(headers);
        // 设置列宽
        ui->prescription_tab_widget->setColumnWidth(0, 100); // 日期列宽
        ui->prescription_tab_widget->setColumnWidth(1, 150); // 药品名列宽
        ui->prescription_tab_widget->setColumnWidth(2, 100); // 使用频次列宽
        ui->prescription_tab_widget->setColumnWidth(3, 100); // 剂量列宽
        ui->prescription_tab_widget->setColumnWidth(4, 100); // 开销列宽
        ui->prescription_tab_widget->setColumnWidth(5, 100); // 对应的医嘱ID列宽
    }

    // 检查是否获取到处方信息
    if (!prescription.isEmpty()) {
        // 插入新行
        int row = ui->prescription_tab_widget->rowCount();
        ui->prescription_tab_widget->insertRow(row);

        // 填充日期
        QString currentTime = Config::getCurrentTime();
        ui->prescription_tab_widget->setItem(row, 0, new QTableWidgetItem(currentTime));
        // 填充药品名
        ui->prescription_tab_widget->setItem(row, 1, new QTableWidgetItem(prescription["medication_name"].toString()));
        // 填充使用频次
        ui->prescription_tab_widget->setItem(row, 2, new QTableWidgetItem(prescription["frequency"].toString()));
        // 填充剂量
        ui->prescription_tab_widget->setItem(row, 3, new QTableWidgetItem(prescription["dosage"].toString()));
        // 填充开销
        ui->prescription_tab_widget->setItem(row, 4, new QTableWidgetItem(prescription["cost"].toString()));
        // 填充对应的医嘱ID
        ui->prescription_tab_widget->setItem(row, 5, new QTableWidgetItem(prescription["advice_id"].toString()));
    } else {
        LOG_ERROR() << "No prescription found for user_id: " << user_id;
    }
}


// 信号发出的地方（on_health_assessment_btn_clicked）
void Widget_patient::on_health_assessment_btn_clicked()
{
    // 发出信号，要求显示健康评估客户端
    emit requestShowHealthAssessmentClient();
}

// 处理信号的槽函数，显示健康评估客户端窗口
void Widget_patient::showHealthAssessmentClient()
{
    HealthAssessmentClient *client = new HealthAssessmentClient();  // 使用动态分配
    client->setWindowTitle("健康评估客户端");
    client->resize(300, 400);
    client->show();  // 显示窗口
}

//void Widget_patient::showChatClient()
//{
//    ChatWidget *chatWidget = new ChatWidget("patient");
//    chatWidget->show();
//}

void Widget_patient::on_chat_btn_clicked()
{
    emit requestChatClient();
}
